package com.tutk.P2PCam264;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;



import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.innosmart.aq.R;

public class SplashScreenActivity extends AppCompatActivity {

	private static final int SPLASH_DISPLAY_TIME = 2000; /* 2 seconds */
	private static boolean isFirstLaunch = true;
	
	private List<MyCamera> cameraList = new ArrayList<MyCamera>();
	private List<DeviceInfo> deviceList = Collections.synchronizedList(new ArrayList<DeviceInfo>());
	
	private DatabaseManager dbManager;
	private ProgressDialog pdialog;
	private int devCnt = 0;


	/**
	 * 该变量用于标示是否检测UID
	 */
	public static boolean isCheckUid = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.splash);
		
		dbManager = new DatabaseManager(this,9);
		
		MyCamera.init();

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

		// VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE);
		
		String versionName = "";
		try {
			versionName = this.getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
		}
		Splash splash = (Splash) findViewById(R.id.splash);
		if (splash != null) {
			splash.setVersion(versionName);
			if (!isFirstLaunch) {
				splash.setVisibility(View.INVISIBLE);
			}
			else{
				// Clean connection leaved by crash last time
				SharedPreferences settings = this.getSharedPreferences("ProcessList", 0);
				if(settings != null){
					
					int killpid = settings.getInt("pid", 0);
					android.os.Process.killProcess(killpid);
					
					int pid = android.os.Process.myPid();
					SharedPreferences.Editor PE = settings.edit();
					PE.putInt("pid", pid);
					PE.commit();
				}
				// End of clean
			}
		}

		
//		new Handler().postDelayed(new Runnable() {
//			@Override
//			public void run() {
//
//				Intent mainIntent = new Intent(SplashScreenActivity.this, MainActivity.class);
//				// mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
//				// Intent.FLAG_ACTIVITY_CLEAR_TOP);
//				SplashScreenActivity.this.startActivity(mainIntent);
//				SplashScreenActivity.this.finish();
//
//				overridePendingTransition(R.anim.mainfadein, R.anim.splashfadeout);
//			}
//		}, isFirstLaunch ? SPLASH_DISPLAY_TIME : 500);
//		pdialog = ProgressDialog.show(this, null, getText(R.string.txtLoadEventList),false,false);

		if (isCheckUid){
			getDevList();
			TenvisUtil tenvis = null;
			devCnt = cameraList.size();
			if(devCnt>0){
				for(MyCamera camera : cameraList){
					tenvis = new TenvisUtil(SplashScreenActivity.this, handler_tenvis);
					tenvis.setValue(camera.getName(), camera.getUID(), camera.getPassword());
					tenvis.exce();
				}
			}else{
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						Intent mainIntent = new Intent(SplashScreenActivity.this,MainActivity.class);
						SplashScreenActivity.this.startActivity(mainIntent);
						SplashScreenActivity.this.finish();
						overridePendingTransition(R.anim.mainfadein, R.anim.splashfadeout);
					}
				}, isFirstLaunch ? SPLASH_DISPLAY_TIME : 500);
				isFirstLaunch = false;
			}
		}else{
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					Intent mainIntent = new Intent(SplashScreenActivity.this,MainActivity.class);
					SplashScreenActivity.this.startActivity(mainIntent);
					SplashScreenActivity.this.finish();
					overridePendingTransition(R.anim.mainfadein, R.anim.splashfadeout);
				}
			}, isFirstLaunch ? SPLASH_DISPLAY_TIME : 500);
			isFirstLaunch = false;
		}
	}
	
	private int backCount = 0;
	private String uidNeddToTipUser = "";
	
	Handler handler_tenvis = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what == 0){
				backCount ++;
				final String resultUID = msg.obj.toString();
				if(resultUID!=null && resultUID.contains("#")){
					String [] arr = resultUID.split("#");
					if(arr!=null && arr.length == 2){
						final String new_uid = arr[0];
						final String old_uid = arr[1];
						if(!old_uid.equals(new_uid)){
							//update db
							dbManager.updateDevUid(old_uid, new_uid);
							//tip
							uidNeddToTipUser = new_uid;
						}
					}
				}
				
				if(backCount == devCnt){
					if(pdialog!=null){
						pdialog.dismiss();
						pdialog = null;
					}
					//Toast.makeText(SplashScreenActivity.this, backCount+"---backcnt---"+devCnt+"-----devCnt", Toast.LENGTH_SHORT).show();
					Intent mainIntent = new Intent(SplashScreenActivity.this, MainActivity.class);
					mainIntent.putExtra("tip", uidNeddToTipUser);
					SplashScreenActivity.this.startActivity(mainIntent);
					SplashScreenActivity.this.finish();
					overridePendingTransition(R.anim.mainfadein, R.anim.splashfadeout);
				}
			}
		};
	};
	
	private void getDevList() {
		DatabaseManager manager = new DatabaseManager(this);
		SQLiteDatabase db = manager.getReadableDatabase();
		Cursor cursor = db.query(DatabaseManager.TABLE_DEVICE, new String[] {
				"_id", "dev_nickname", "dev_uid", "dev_name", "dev_pwd",
				"view_acc", "view_pwd", "event_notification", "camera_channel",
				"snapshot", "ask_format_sdcard" }, null, null, null, null,
				"_id LIMIT " + MainActivity.CAMERA_MAX_LIMITS);

		while (cursor.moveToNext()) {

			long db_id = cursor.getLong(0);
			String dev_nickname = cursor.getString(1);
			String dev_uid = cursor.getString(2);
			String view_acc = cursor.getString(5);
			String view_pwd = cursor.getString(6);
			int event_notification = cursor.getInt(7);
			int channel = cursor.getInt(8);
			byte[] bytsSnapshot = cursor.getBlob(9);
			int ask_format_sdcard = cursor.getInt(10);
			Bitmap snapshot = (bytsSnapshot != null && bytsSnapshot.length > 0) ? DatabaseManager
					.getBitmapFromByteArray(bytsSnapshot) : null;

			MyCamera camera = new MyCamera(dev_nickname, dev_uid, view_acc,
					view_pwd);
			DeviceInfo dev = new DeviceInfo(db_id, camera.getUUID(),
					dev_nickname, dev_uid, view_acc, view_pwd, "",
					event_notification, channel, snapshot);
			dev.ShowTipsForFormatSDCard = ask_format_sdcard == 1;
			deviceList.add(dev);

			cameraList.add(camera);
		}

		cursor.close();
		db.close();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}
}